package com.csp.mingyue.common.feign.interceptor;

import cn.dev33.satoken.same.SaSameUtil;
import cn.hutool.core.util.StrUtil;
import com.csp.mingyue.common.core.utils.IpUtils;
import com.csp.mingyue.common.core.utils.ServletUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * Feign 请求拦截器
 *
 * @author Strive
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

	@Override
	public void apply(RequestTemplate requestTemplate) {
		HttpServletRequest httpServletRequest = ServletUtils.getRequest();
		if (Objects.nonNull(httpServletRequest)) {
			Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
			// 传递用户信息请求头，防止丢失
			String Authentication = headers.get(HttpHeaders.AUTHORIZATION);
			if (StrUtil.isNotBlank(Authentication)) {
				requestTemplate.header(HttpHeaders.AUTHORIZATION, Authentication);
			}

			// 为 Feign 的 RCP 调用，添加请求头 Same-Token
			requestTemplate.header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken());

			// 配置客户端IP
			requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr());
		}
	}

}
